<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="85%"
    title="同步商品至门店"
    :style="{ top: '20px' }"
    destroy-on-close
  >
    <a-form ref="form" :model="formData">
      <a-row>
        <a-col :span="24">
          <a-form-item
            :label="''"
            :name="['allRetailFlag']"
            :rules="[
              {
                required: true,
                message: '请选择同步商品',
                validator: (_rule, value, callback) => {
                  if (tableData.length === 0) {
                    return callback('请选择同步商品');
                  }
                  return callback();
                },
              },
            ]"
          >
            <vxe-grid
              ref="syncGrid"
              resizable
              show-overflow
              highlight-hover-row
              keep-source
              row-id="id"
              :loading="loading"
              :height="600"
              :data="tableData"
              :columns="tableColumn"
              :toolbar-config="toolbarConfig"
              :scroll-y="virtualYConfig"
            >
              <!-- 工具栏 -->
              <template #toolbar_buttons>
                <a-row>
                  <a-col :span="24">
                    <a-form-item
                      label="同步门店"
                      prop="shopIds"
                      :rules="[{ required: true, message: '请选择同步门店' }]"
                    >
                      <shop-selector v-model:value="formData.shopIds" multiple showSum />
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item
                      label="同步商品"
                      prop="allRetailFlag"
                      :rules="[{ required: true, message: '请选择同步商品' }]"
                    >
                      <a-space>
                        <a-radio-group
                          v-model:value="formData.allRetailFlag"
                          :options="[
                            { label: '全部', value: true },
                            { label: '部分', value: false },
                          ]"
                          @change="() => (tableData = [])"
                        />
                        <a-button
                          v-if="!formData.allRetailFlag"
                          type="primary"
                          @click="openSelectorDialog"
                        >
                          选择同步商品
                        </a-button>
                        <a-button v-else type="primary" @click="loadAllProducts">
                          加载全部商品
                        </a-button>
                      </a-space>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item
                      label="同步数据"
                      prop="purchasePrice"
                      :rules="[{ required: true, message: '请选择同步数据' }]"
                    >
                      <a-space>
                        <a-checkbox v-model:checked="formData.purchasePrice">采购价</a-checkbox>
                        <a-checkbox v-model:checked="formData.salePrice">销售价</a-checkbox>
                        <a-checkbox v-model:checked="formData.retailPrice">零售价</a-checkbox>
                        <a-checkbox v-model:checked="formData.available">状态</a-checkbox>
                      </a-space>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-button danger @click="delSyncProduct">删除</a-button>
                  </a-col>
                </a-row>
              </template>
              <!-- 同步状态列 -->
              <template #syncStatus_default="{ row }">
                <a-space>
                  <span v-if="row.syncStatus === 0">
                    <PauseCircleFilled :style="{ fontSize: '18px', color: '#bfbfbf' }" />
                    取消同步
                  </span>
                  <span v-if="row.syncStatus === 1">
                    <PlayCircleFilled :style="{ fontSize: '18px', color: '#faad14' }" />
                    等同步
                  </span>
                  <span v-if="row.syncStatus === 2">
                    <SyncOutlined :style="{ fontSize: '18px', color: '#0050b3' }" spin />
                    同步中
                  </span>
                  <span v-if="row.syncStatus === 3">
                    <CheckCircleFilled :style="{ fontSize: '18px', color: '#52c41a' }" />
                    同步完成
                  </span>
                  <span v-if="row.syncStatus === 4">
                    <CloseCircleFilled :style="{ fontSize: '18px', color: '#ff4d4f' }" />
                    同步失败
                  </span>
                </a-space>
              </template>
              <!-- 操作列 -->
              <template #action_default="{ rowIndex, row }">
                <a-space>
                  <a-button
                    type="primary"
                    html-type="submit"
                    :loading="syncLoading || row.loading"
                    @click="syncProduct(row)"
                  >
                    同步
                  </a-button>
                  <a-button
                    danger
                    :disabled="syncLoading || row.loading"
                    @click="() => tableData.splice(rowIndex, 1)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </vxe-grid>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <div class="form-modal-footer">
        <a-space>
          <a-button
            type="primary"
            html-type="submit"
            :loading="loading || syncLoading"
            @click="syncAllProduct"
          >
            全部同步
          </a-button>
          <a-button :loading="loading || syncLoading" @click="closeDialog">取消</a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
  <!-- 零售品选择器 -->
  <retail-selector-dialog
    v-if="syncType === 'retail'"
    ref="retailSelectorDialogRef"
    :shop-id="props.shopId"
    @confirm="onConfirm"
  />
  <!-- 销售品选择器 -->
  <sales-selector-dialog
    v-if="syncType === 'sales'"
    ref="salesSelectorDialogRef"
    :shop-id="props.shopId"
    @confirm="onConfirm"
  />
  <!-- 原材料选择器 -->
  <materials-selector-dialog
    v-if="syncType === 'materials'"
    ref="materialsSelectorDialogRef"
    :shop-id="props.shopId"
    @confirm="onConfirm"
  />
</template>

<script setup>
  import { getCurrentInstance, ref } from 'vue';
  import * as api from '@/api/base-data/product/info';
  import {
    PauseCircleFilled,
    PlayCircleFilled,
    SyncOutlined,
    CheckCircleFilled,
    CloseCircleFilled,
  } from '@ant-design/icons-vue';
  import ShopSelector from '@/components/Selector/src/ShopSelector.vue';
  import RetailSelectorDialog from '@/views/base-data/product/info/retailSelectorDialog.vue';
  import SalesSelectorDialog from '@/views/base-data/product/info/salesSelectorDialog.vue';
  import MaterialsSelectorDialog from '@/views/base-data/product/info/materialsSelectorDialog.vue';

  defineOptions({
    name: 'SyncDialog',
  });

  // this对象
  const instance = getCurrentInstance();

  const emit = defineEmits(['confirm', 'close']);

  const visible = ref(false);

  const form = ref();

  const syncGrid = ref();

  const loading = ref(false);

  const syncLoading = ref(false);

  const retailSelectorDialogRef = ref();

  const salesSelectorDialogRef = ref();

  const materialsSelectorDialogRef = ref();

  const props = defineProps({
    syncType: {
      type: String,
      required: true,
    },
    shopId: {
      type: String,
      default: '',
    },
  });

  const syncTypeMapping = {
    // 零售品
    retail: {
      ref: 'retailSelectorDialogRef',
      categoryTypes: '3,4',
    },
    // 销售品
    sales: {
      ref: 'salesSelectorDialogRef',
      categoryTypes: '2',
    },
    // 原材料
    materials: {
      ref: 'materialsSelectorDialogRef',
      categoryTypes: '1',
    },
  };

  const formData = ref({
    shopIds: [],
    allRetailFlag: true,
    purchasePrice: true,
    salePrice: true,
    retailPrice: true,
    properties: true,
    available: true,
  });

  const tableData = ref([]);

  // 表格列配置
  const tableColumn = ref([
    { type: 'checkbox', width: 45 },
    { field: 'code', title: '商品编号', width: 120 },
    { field: 'name', title: '商品名称', width: 160 },
    { field: 'skuCode', title: '商品SKU编号', width: 120 },
    { field: 'externalCode', title: '商品简码', width: 120 },
    { field: 'categoryName', title: '商品分类', width: 120 },
    { field: 'brandName', title: '商品品牌', width: 120 },
    {
      field: 'productType',
      title: '商品类型',
      width: 120,
      formatter: ({ cellValue }) => {
        return _This().$enums.PRODUCT_TYPE.getDesc(cellValue);
      },
    },
    {
      field: 'syncStatus',
      title: '同步状态',
      minWidth: 120,
      slots: { default: 'syncStatus_default' },
    },
    {
      title: '操作',
      width: 150,
      fixed: 'right',
      slots: { default: 'action_default' },
    },
  ]);

  // 工具栏配置
  const toolbarConfig = ref({
    // 缩放
    zoom: false,
    // 自定义表头
    custom: false,
    // 右侧是否显示刷新按钮
    refresh: false,
    // 自定义左侧工具栏
    slots: {
      buttons: 'toolbar_buttons',
    },
  });

  // 虚拟滚动配置
  const virtualYConfig = ref({
    enabled: true,
    gt: 0,
  });

  // 打开弹窗
  const openDialog = () => {
    visible.value = true;
    initData();
  };

  // 关闭对话框
  const closeDialog = () => {
    visible.value = false;
    emit('close');
  };

  // 初始化数据
  const initData = () => {
    formData.value = {
      shopIds: [],
      allRetailFlag: true,
      purchasePrice: true,
      salePrice: true,
      retailPrice: true,
      properties: true,
      available: true,
    };
    tableData.value = [];
  };

  // 打开选择对话框
  const openSelectorDialog = () => {
    if (props.syncType === 'retail') {
      retailSelectorDialogRef.value.openDialog();
    } else if (props.syncType === 'sales') {
      salesSelectorDialogRef.value.openDialog();
    } else if (props.syncType === 'materials') {
      materialsSelectorDialogRef.value.openDialog();
    }
  };

  // 确认选择
  const onConfirm = (selectedRows) => {
    loading.value = true;
    const dataList = [...tableData.value];
    for (const item of selectedRows) {
      const exist = !!tableData.value.find((tableItem) => tableItem.id === item.id);
      if (!exist) {
        dataList.push({
          ...item,
          syncSwitch: true,
          syncStatus: 1,
        });
      }
    }
    syncGrid.value.reloadData(dataList).then(() => {
      _This().$msg.createSuccess(`加载商品 ${dataList.length} 条`);
      tableData.value = dataList;
      loading.value = false;
    });
  };

  // 删除选中商品
  const delSyncProduct = () => {
    const records = syncGrid.value.getCheckboxRecords();
    if (_This().$utils.isEmpty(records)) {
      _This().$msg.createError('请选择要删除的规格数据！');
      return;
    }

    _This()
      .$msg.createConfirm('是否确定删除选中的数据？')
      .then(() => {
        tableData.value = tableData.value.filter((t) => {
          const tmp = records.filter((item) => item.id === t.id);
          return _This().$utils.isEmpty(tmp);
        });
      });
  };

  // 加载所有商品
  const loadAllProducts = () => {
    loading.value = true;
    api
      .query({
        pageIndex: 1,
        pageSize: 5000,
        categoryTypes: syncTypeMapping[props.syncType]?.categoryTypes,
        shopId: props.shopId,
        available: true,
      })
      .then((res) => {
        onConfirm(res.datas);
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 同步商品
  const syncProduct = async (row, validate = true) => {
    if (validate) {
      await form.value.validate();
    }
    row.loading = true;
    row.syncStatus = 2;
    await api
      .syncProductShop({
        productId: row.id,
        shopId: formData.value.shopIds.join(','),
        purchasePrice: formData.value.purchasePrice,
        salePrice: formData.value.salePrice,
        retailPrice: formData.value.retailPrice,
        properties: formData.value.properties,
        available: formData.value.available,
      })
      .then(() => {
        row.syncStatus = 3;
      })
      .catch(() => {
        row.syncStatus = 4;
      })
      .finally(() => {
        row.loading = false;
      });
  };

  // 全部同步商品
  const syncAllProduct = () => {
    form.value.validate().then(async () => {
      syncLoading.value = true;
      tableData.value.forEach((item) => (item.syncStatus = 1));
      const promises = tableData.value.map((item) => syncProduct(item, false));
      Promise.all(promises)
        .then(() => {
          _This().$msg.createSuccess('全部商品同步完成！');
        })
        .finally(() => {
          syncLoading.value = false;
        });
    });
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  defineExpose({
    openDialog,
  });
</script>

<style scoped></style>
